/**
 * desc :
 * User : hjt
 * Date : 2017/1/20
 */
var http = require("http");
var fs = require("fs");
//mine的github地址：https://github.com/broofa/node-mime
var mime = require("mime");
var path = require('path');

//读取配置文件
var httpJsonString = fs.readFileSync(__dirname + "/config/http.json", "utf8");
var httpJson = JSON.parse(httpJsonString);

//创建服务
http.createServer(function(req, res){
    //静态文件的处理
    var path = req.url.replace(/\/?(?:\?.*)?$/,"").replace();
    getResourcesData(res, path);
}).listen(httpJson.port, httpJson.hostname);

//读取资源文件
function getResourcesData(res, path, statusCode){
    if(!statusCode) statusCode = 200;
    var mimeType = mime.lookup(path) || "text/plain";
    //如果是图片文件
    if(mimeType != "text/html"){
        //二进制文件的处理,不许缓存处理。如果不缓存，每次请求请求都会进行服务器下载。这里一定要做处理
        path = "/public" + path;
    } else {
        path = "/view" + path;
    }

    fs.readFile(__dirname + path, function(err, data){
        if(err){
            res.writeHead(404,{"Content-Type":"text/plain"});
            res.end("404 - Not Found Resources ");
        } else {
            res.writeHead(statusCode,{"Content-Type":mimeType});
            res.end(data);
            if(mimeType!="text/html"){
                //客户端的缓存处理，根据时间戳去处理掉，资源文件.
            }
        }
    });

}

console.log("你当前服务器已经启动：端口是:"+httpJson.port+",访问地址是：http://:"+httpJson.hostname+":"+httpJson.port);
